import React from 'react';

import format from 'lib/util/format';
import View from 'lib/View.jsx';
import Card from 'lib/components/card.jsx';
import ChartWidget from 'lib/components/ChartWidget.jsx';
import Tab from 'lib/components/tab.jsx';
import GridWidget from 'lib/components/GridWidget.jsx';
import Resizable from 'lib/components/Resizable.jsx';
import DefaultLoadingElement from 'lib/util/defaultLoadingElement.jsx';
import DefaultErrorElement from 'lib/util/defaultErrorElement.jsx';
import dispatcher from 'lib/dispatcher'

import DrillScope from './DrillScope.es6';

export default class DrillView extends View {
  inputIndexHandler(e) {
    if (!e.ctrlKey && !e.altKey && !e.shiftKey && e.charCode === 13) {
      this.fastIndexHandler(parseInt(e.target.value));
    }
  } // inputIndexHandler

  fastIndexHandler(index) {
    if (!isNaN(index) && index >= 1 && index <= this.state.basicInfo.count) {
      dispatcher.dispatch({
        $type:'select_indexed_value',
        index
      });
    }
  }

  getResponseData() {
    try {
      return (
        <pre style={{margin:'auto'}}>
          {JSON.stringify(JSON.parse(this.state.dataGrid.data.data), null, 2)}
        </pre>
      );
    } catch (e) {
      return this.state.dataGrid.data.data;
    }
  }

  onSwitch(index){
    if(index===1){
      this.scope.fetchDataGrid()
    }else{
      this.scope.fetchUserInfo()
    }
  }

  render() {
    return (
      <div className="box">
        <Card className="widget-float" title={this.state.title} extra={
          <a className="close iconfont" href="javascript:;" style={{marginTop:'5px'}} onClick={this.props.history.goBack}>&#xe638;</a>
        }>
          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Card>
                  <div className="pure-g">
                    <div className="pure-u-5-24">
                      <b>请求类型：</b>{this.state.traceType==='slow'?'慢请求':'错误请求'}
                    </div>
                    <div className="pure-u-9-24">
                      <b>最近采集时间：</b>{this.state.basicInfo.lastTime}
                    </div>
                    <div className="pure-u-4-24">
                      <b>采集次数：</b>{this.state.basicInfo.count}
                    </div>
                    <div className="pure-u-6-24">
                      <b>平均响应时间：</b>{this.state.basicInfo.avgTimeForResponse}
                    </div>
                  </div>
                </Card>
              </div>
            </div>
          </div>
          <div className="pure-g">
          {
            this.state.traceType === 'error'
              ? (
                <div className="pure-u-1-3">
                  <div className="box">
                    <Card title="状态码分布">
                      <ChartWidget store={this.state.pie0} chartType="pie" chartSettings={this.state.pieChartSettings} />
                    </Card>
                  </div>
                </div>
              ) : null
          }
            <div className={'pure-u-1-' + (this.state.traceType === 'error' ? 3 : 2)}>
              <div className="box">
                <Card title="地域分布">
                  <ChartWidget store={this.state.pie1} chartType="pie" chartSettings={this.state.pieChartSettings} />
                </Card>
              </div>
            </div>
            <div className={'pure-u-1-' + (this.state.traceType === 'error' ? 3 : 2)}>
              <div className="box">
                <Card title="运营商分布">
                  <ChartWidget store={this.state.pie2} chartType="pie" chartSettings={this.state.pieChartSettings} />
                </Card>
              </div>
            </div>
          </div>
          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Tab onAfterChange={this.onSwitch.bind(this)}>
                  <Tab.Panel title="Ajax请求详情" key="ajaxrequest">
                    <Card title="Ajax 请求详情" extra={
                      <div style={{
                        textAlign:'right',
                        margin:'-7px auto auto'
                      }}>
                        <div className="trace-cross-title" style={{
                          width:'300px',
                          display:'inline-block',
                          marginRight:'-55px'
                        }}>
                          <span className="previous" onClick={this.fastIndexHandler.bind(this, this.state.dataOffset - 1)}>
                            <i href="javascript:;" className="iconfont">&#xe658;</i>
                          </span>
                          <span style={{lineHeight:'40px',margin:'auto'}}>
                            第
                            <input
                              key={this.state.dataOffset}
                              className="input-text"
                              type="text"
                              defaultValue={this.state.dataOffset}
                              style={{
                                display: 'inline-block',
                                width: '36px',
                                height: '19px',
                                fontSize: '13px',
                                padding: '5px 5px',
                                margin: 'auto 10px'
                              }}
                              onKeyPress={this.inputIndexHandler.bind(this)} />
                            条
                          </span>
                          <span className="next" onClick={this.fastIndexHandler.bind(this, this.state.dataOffset + 1)}>
                            <i href="javascript:;" className="iconfont">&#xe659;</i>
                          </span>
                        </div>
                        <span>共 {this.state.basicInfo.count} 条</span>
                      </div>
                    }>
                    {
                      !this.state.dataGrid.data
                        ? (this.state.dataGrid.loading ? (<DefaultLoadingElement />) : (<DefaultErrorElement />))
                        : (
                          <table className="table table-striped ajax-detail-table">
                            <colgroup>
                              <col key={0} width="20%"/>
                              <col key={1} width="80%"/>
                            </colgroup>
                            <tbody>
                            <tr>
                              <td width="20%"><b>请求开始时间</b></td>
                              <td width="80%">{format.stampToTime(this.state.dataGrid.data.dataTime)}</td>
                            </tr>
                            <tr>
                              <td><b>地域/运营商</b></td>
                              <td>{`${this.state.dataGrid.data.countryName}${this.state.dataGrid.data.regionName} / ${this.state.dataGrid.data.networkOperator||''}`}</td>
                            </tr>
                            <tr>
                              <td><b>请求方式</b></td>
                              <td>{this.state.dataGrid.data.method}</td>
                            </tr>
                            <tr>
                              <td><b>请求 headers</b></td>
                              <td><pre style={{margin:'auto'}}>{JSON.stringify(JSON.parse(this.state.dataGrid.data.requestHeader), null, 2)}</pre></td>
                            </tr>
                            <tr>
                              <td><b>响应 headers</b></td>
                              <td>
                                <Resizable useLoadFire={false} onResize={ () => this.forceUpdate()}>
                                <div style={{ width: document.getElementsByClassName('widget-float')[0].offsetWidth * 0.79,'overflowX': 'auto' }}>
                                  <pre style={{margin:'auto'}}>
                                    {JSON.stringify(JSON.parse(this.state.dataGrid.data.responseHeader), null, 2)}
                                  </pre>
                                </div>
                                </Resizable>
                              </td>
                            </tr>
                            <tr>
                              <td><b>状态码</b></td>
                              <td>{this.state.dataGrid.data.statusCode}</td>
                            </tr>
                            <tr>
                              <td><b>statusText</b></td>
                              <td>{this.state.dataGrid.data.statusText}</td>
                            </tr>
                            <tr>
                              <td><b>响应的data</b></td>
                              <td>{this.getResponseData()}</td>
                            </tr>
                            <tr>
                              <td><b>响应的url</b></td>
                              <td>{this.state.dataGrid.data.responseUrl}</td>
                            </tr>
                            <tr>
                              <td><b>执行时间</b></td>
                              <td>{format.numSecs(this.state.dataGrid.data.totalTime)}</td>
                            </tr>
                            </tbody>
                          </table>
                        )
                    }
                    </Card>
                  </Tab.Panel>
                  <Tab.Panel title="用户信息" key="userinfo">
                  {
                    this.state.userInfoGrid.loading
                      ? (
                          <Card>
                            <DefaultLoadingElement style={{color:'black'}} />
                          </Card>
                      ) : (
                        <div>
                          <Card>
                            <GridWidget store={this.state.userInfoGrid} cols={this.state.userInfoCols} nodataElement={"暂无影响用户信息"}/>
                          </Card>
                        </div>
                      )
                  }
                  </Tab.Panel>
                </Tab>
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  }
}

DrillView.defaultProps = {
  Scope:DrillScope
}
